package com.zch.socket.aio.server2;

import com.zch.socket.aio.server.ServerProvider;
import com.zch.socket.common.model.RequestModel;
import com.zch.socket.common.model.ResponseModel;

import java.io.IOException;
import java.net.SocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * 服务端接收客户端的处理器
 */
public class ServerAcceptHandler implements CompletionHandler<AsynchronousSocketChannel,Object> {



    /**
     * 成功接受客户端连接
     * @param chanel
     * @param attachment
     */
    @Override
    public void completed(AsynchronousSocketChannel chanel, Object attachment) {
       System.out.println("客户端已成功连接");
        //继续接受其他客户端的请求
        Server.clientCount++;
        System.out.println("连接的客户端数：" + Server.clientCount);
        //创建新的Buffer
       ByteBuffer buffer=ByteBuffer.allocate(1024);
        //异步读  第三个参数为接收消息回调的业务Handler
        chanel.read(buffer, buffer,new ServerReadHandler(chanel));
    }

    /**
     * 接收客户端连接异常
     * @param exc
     * @param attachment
     */
    @Override
    public void failed(Throwable exc, Object attachment) {
       System.out.println("客户端连接异常");
       exc.printStackTrace();
    }
}
